var api = require('../../utils/api.js')
var app = getApp();
var util = require('../../utils/util.js');

Page({
  data: {
    income_type: 0, //收入来源 0:全部 1:门店 2:小店
    currentTime: 0, //日期筛选参数,0累计 1今日 2本周 3本月 4本年
    times: ['累计', '今日', '本周', '本月', '本年'],
    showDateChoose: true, //是否显示日期筛选
    sales: [], //明细列表
    showSaleDetail: true, //是否显示收入明细列表
    inputDateHidden: true, //是否隐藏自定义日期输入框
    endDate: "",
    startDate: "",
    page: 1,
    limit: 20,
    total_page: 1,
    showRegulations: false,
    income_statement: '暂无',
    showStoreRank: true,
    rank_title_select: 1,
    rank_type: 11,
		select_income_type:1,  //收入筛选
  },


  onShow: function() {
    this.setData({
      redirect_appid: app.globalData.redirect_appid, //判断是否用户版跳转过来的
    })
    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    if (month < 10) {
      month = '0' + month;
    };
    if (day < 10) {
      day = '0' + day;
    };
    var formatDate = year + '-' + month + '-' + day;
    this.setData({
      endDate: formatDate,
      startDate: "请选择开始日期",
      ofEndDate: formatDate,
    })
    //summernew0303
    // this.autoLogin();
    var isLogin = wx.getStorageSync("isLogin");
    if (isLogin == 1) {
      this.autoLogin();
    }else{
      wx.redirectTo({
        url: '../beforeLogin/beforeLogin?login_error_code=11906',
      })
    }

  },

  // 自动登录
  autoLogin: function() {
    var that = this;
    wx.login({
      success: function(res) {
        if (res.code) {
          var code = res.code;
          var params = new Object()
          params.code = code;
          api.POST({
            params: params,
            url: app.globalData.login_url,
            success: function(respone) {
              util.hiddenLoading();
              if (respone.data.code) {
                switch (respone.data.code) {
                  case '11906':
                    wx.redirectTo({
                      url: '../beforeLogin/beforeLogin?login_error_code=11906',
                    });
                    break;
                  case '5802':
                    util.showError("密码错误");
                    break;
                  case '2499':
                    util.showError("该账号已经绑定过其他微信账号了");
                    break;
                  default:
                    util.showError(respone.data.message);
                    break;
                }
              } else {
                app.globalData.loginState = 1;
                wx.setStorageSync("isLogin", "1");
                var accountInfo = respone.data.data.result;
                console.log(accountInfo);
                app.globalData.accountInfo = accountInfo;
                // accountInfo.type=1;
                that.setData({
                  accountInfo: accountInfo
                });
                that.refreshData();
              }
            },
            fail: function() {
              util.hiddenLoading();
            }
          })
        }
      },
      fail: function() {
        util.showError("网络错误，请检查网络。");
      }
    })
  },

  //刷新数据
  refreshData: function() {
    var that = this;
    this.setData({
      page: 1,
      total_page: 1
    })
    wx.showLoading({
      title: '加载中',
    })
    setTimeout(function() {
      that.loadShopSaleStatisticsData();
      that.loadShopSaleDetailData();
    }, 300)
  },

  // 收入统计
  loadShopSaleStatisticsData: function() {
    var that = this;
    var params = new Object()
    params.time = that.data.currentTime;

    if (that.data.currentTime == 0) {
      params.start_time = that.data.startDate;
      params.end_time = that.data.endDate;
    }
    if (that.data.accountInfo.type == 1) {
      //运营商
      var url = app.globalData.base_url + 'shop/merchantSaleStatistics';
    } else {
      //（门店和小店合并统计）
      params.type = that.data.income_type;
      var url = app.globalData.base_url + 'shop/incomeSIStatistics';
    }
    api.POST({
      url: url,
      params: params,
      success: function(res) {
        util.hiddenLoading();
        that.setData({
          saleSatistics: res.data.data,
        })
      },
    })
  },

  // 收入明细
  loadShopSaleDetailData: function() {
    var that = this;
    var params = new Object()
    params.page = that.data.page;
    params.limit = that.data.limit;
    params.time = that.data.currentTime;
    if (that.data.currentTime == 0) {
      params.start_time = that.data.startDate;
      params.end_time = that.data.endDate;
    }
    if (that.data.accountInfo.type == 1) {
      //运营商
			if (that.data.rank_title_select==2){
				params.income_type = that.data.select_income_type
			}
      params.group_type = that.data.rank_title_select;
      var rank_type = String(that.data.rank_type);
      params.sort_field = rank_type.substring(0, 1);
      params.sort_type = rank_type.substring(1);
      var url = app.globalData.base_url + 'shop/merchantIncomeStatistics';
    } else {
      //门店和小店合并统计
      params.type = that.data.income_type;
      var url = app.globalData.base_url + 'shop/incomeSIDetail';
    }
    api.POST({
      url: url,
      params: params,
      success: function(res) {
        util.hiddenLoading();
        wx.stopPullDownRefresh();
        if (res.data.code) {
          util.showError(res.data.message);
          return false;
        }
        var paging = res.data.data.paging;
        that.setData({
          page: paging.page,
          total_page: paging.total_page
        })
        var currentSaleDetail = res.data.data.list;
        if (that.data.page == 1) {
          var saleDetailLists = currentSaleDetail;
        } else {
          var saleDetailLists = that.data.sales.concat(currentSaleDetail);
        }
        if (saleDetailLists.length > 0) {
          that.setData({
            sales: saleDetailLists,
            showSaleDetail: true,
          })
        } else {
          that.setData({
            sales: [],
            showSaleDetail: false
          })
        }
      },
      fail: function(res) {
        util.hiddenLoading();
        wx.stopPullDownRefresh();
      }
    })
  },

  //切换收入来源
  incomeType: function(e) {
    var that = this;
    var type = e.currentTarget.dataset.types;
    if (type != this.data.income_type) {
      that.setData({
        income_type: type
      })
      that.refreshData();
    }
  },

  // 切换日期
  swichNav: function(e) {
    var that = this;
    var currentTime = e.target.dataset.currentTime;
    this.setData({
      currentTime: currentTime,
      showDateChoose: (currentTime == 0) ? true : false
    });
   that.refreshData();
  },

  //自定义日期是否隐藏
  actionDayChoose: function(e) {
    this.setData({
      inputDateHidden: !this.data.inputDateHidden
    })
  },

  //加载更多
  onReachBottom: function() {
    var that = this;
    if (this.data.page < this.data.total_page) {
      this.setData({
        page: ++this.data.page
      })
      setTimeout(function() {
        that.loadShopSaleDetailData();
      }, 300)
    }
  },

  //下拉刷新
  onPullDownRefresh: function() {
    this.refreshData();
  },

  //输入开始日期
  startDateChange: function(e) {
    this.setData({
      startDate: e.detail.value
    })
  },

  //输入结束日期
  endDateChange: function(e) {
    this.setData({
      endDate: e.detail.value
    })
  },

  //时间筛选
  confirm: function() {
    var that = this;
    var start_time = '',
      end_time = '';
    var a = /^(\d{4})-(\d{2})-(\d{2})$/
    if (a.test(this.data.startDate)) {
      start_time = this.data.startDate;
    }

    if (a.test(this.data.endDate)) {
      end_time = this.data.endDate;
    }
    this.setData({
      page: 1,
      total_page: 1,
      start_time: start_time,
      end_time: end_time,
      inputDateHidden: true
    })
    that.refreshData();
  },

  //自定义日期取消
  cancel: function() {
    this.setData({
      inputDateHidden: true
    })
  },

  //去酒掌柜用户版
  jiuzhanggui: function() {
    wx.navigateToMiniProgram({
      appId: 'wx2f5360b509c07b8a',
      path: 'pages/index/index',
      envVersion: 'trial', //develop	开发版 trial	体验版  release	正式版
    })
  },

  // 使用规则弹框
  showRegulations: function() {
    var that = this;
    // if (that.data.income_statement == '暂无') {
    //   api.POST({
    //     url: app.globalData.base_url + 'system/set',
    //     params: {},
    //     success: function(res) {
    //       if (res.data.code == '') {
    //         that.setData({
    //           income_statement: res.data.data.income_statement,
    //         })
    //       }
    //     }
    //   })
    // }
    that.setData({
      showRegulations: true
    })
  },
  // 使用规则弹框隐藏
  hiddenRegulations: function() {
    this.setData({
      showRegulations: false
    })
  },

  //运营商销售统计切换
  rank_title_select: function(e) {
    var that = this;
    var rank_title_select = e.currentTarget.dataset.ids;
    if (rank_title_select != that.data.rank_title_select) {
      that.setData({
        rank_title_select: rank_title_select
      });
			that.refreshData();
    }
  },

  //运营商销售排行顺序切换
  rank_type: function(e) {
    var that = this;
    var ids = e.currentTarget.dataset.ids;
    var rank_type = 11;
    if (ids == 1) {
      if (that.data.rank_type == 11) {
        rank_type = 12
      } else {
        rank_type = 11
      }
    } else {
      if (that.data.rank_type == 21) {
        rank_type = 22
      } else {
        rank_type = 21
      }
    }
    that.setData({
      rank_type: rank_type
    })
    that.refreshData();
  },

  //运营商门店详情
  shop_detail: function(e) {
    var ids = e.currentTarget.dataset.ids;
    var types = e.currentTarget.dataset.types;
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: '/pages/shopSales/shopSales?id=' + ids + '&type=' + types + '&name=' + name,
    })
  },


  //退款明细
  refundDetail: function() {
    var startDate = (this.data.startDate == '请选择开始日期' ? '' : this.data.startDate);
    if (this.data.accountInfo.type == 1) {
      //运营商
      var params = 'time=' + this.data.currentTime + '&start_time=' + startDate + '&end_time=' + this.data.endDate
    } else {
      var params = 'type=' + this.data.income_type + '&time=' + this.data.currentTime + '&start_time=' + startDate + '&end_time=' + this.data.endDate
    }
    wx.navigateTo({
      url: '/pages/refundDetail/refundDetail?' + params,
    })
  },

	//运营商商品销量统计筛选
	select_income_type:function(){
		var that=this;
		wx.showActionSheet({
			itemList: ['总收入', '服务费', '提货费'],
			success(res) {
				that.setData({
					select_income_type: (res.tapIndex/1)+1
				})
				that.refreshData();
			},
			fail(res) {
				console.log(res.errMsg)
			}
		})
	},
})